# -*- coding:utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2009 Yuntien.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import urllib2

class SinaTError(Exception):
    pass

class SinaTClient(object):

    def __init__(self):
        self.cookie_str = None
    
    def login(self, user, passwd):
        post = "username=" + user + "&password=" + passwd + "&service=miniblog&encoding=utf-8&gateway=1&savestate=7&useticket=0&url=http%3A%2F%2Ft.sina.com.cn%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META"
        req = urllib2.Request(url='http://login.sina.com.cn/sso/login.php', data=post)
        
        req.add_header("Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*")
        req.add_header("Referer", "http://t.sina.com.cn/login.php?url=http%3A%2F%2Ft.sina.com.cn%2F")
        req.add_header("UserAgent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5")
        req.add_header("ContentType", "application/x-www-form-urlencoded")
        req.add_header("Accept-Language", "zh-CN")
        req.add_header("Accept-Encoding", "gzip, deflate")
        req.add_header("Host","login.sina.com.cn")
        req.add_header("ContentLength",str(len(post)))
        req.add_header("Pragma","no-cache")
        req.add_header("Cookie","_s_upa=5; Apache=74.125.155.141.788991254079255269")
        req.add_header("Cache-Control","no-cache")
        
        f = urllib2.urlopen(req)
        
        cookie_str = f.headers.dict["set-cookie"]
        cookie_str = cookie_str.replace("Httponly,", "")
        cookie_str = cookie_str.replace("Httponly;,", "")
        
        self.cookie_str = cookie_str
        
    def set_cookie_str(self, cookie_str):
        self.cookie_str = cookie_str
        
    def get(self, url):
        if not self.cookie_str:
            raise SinaTError, 'please login..'

        req = urllib2.Request(url=url)
        req.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
        req.add_header("Referer", "http://t.sina.com.cn/home")
        req.add_header("UserAgent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5")
        req.add_header("ContentType", "application/x-www-form-urlencoded; charset=UTF-8")
        req.add_header("Accept-Language", "zh-CN")
        req.add_header("Host", "t.sina.com.cn")
        req.add_header("Pragma", "no-cache")
        req.add_header("Cookie", self.cookie_str)
        
        f = urllib2.urlopen(req)
        return ''.join(f.readlines())        

    def post(self, url, content):
        if not self.cookie_str:
            raise SinaTError, 'please login..'
        
        req = urllib2.Request(url=url, data=content)
        req.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
        req.add_header("Referer", "http://t.sina.com.cn/home")
        req.add_header("UserAgent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5")
        req.add_header("ContentType", "application/x-www-form-urlencoded; charset=UTF-8")
        req.add_header("Accept-Language", "zh-CN")
        req.add_header("Host", "t.sina.com.cn")
        req.add_header("ContentLength", str(len(content)))
        req.add_header("Pragma", "no-cache")
        req.add_header("Cookie", self.cookie_str)
        
        f = urllib2.urlopen(req)
        return ''.join(f.readlines())        

    def publish(self, content):
        content = "content=" + content + "&pic=&from=myprofile";
        content = content.encode('utf-8')
        
        return self.post("http://t.sina.com.cn/mblog/publish.php", content)

    def forward(self, mid, reason):
        content = 'mid=%s&reason=%s' % (mid, reason)
        content = content.encode('utf-8')
        
        return self.post("http://t.sina.com.cn/mblog/forward.php", content)

if __name__ == '__main__':
    client = SinaTClient()
    client.login(user, passwd)
    client.publish('test..')
